<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/employees/excel')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="pageParams.size"
            :current-page="pageParams.page"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20]"
            @current-change="hCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 弹出层 -->
      <el-dialog
        title="添加"
        :visible.sync="showDialog"
        width="50%"
      >
        <employDiolog v-if="showDialog" @close="hClose" @update-empolyee="hUpdateEmpolyee" />
      </el-dialog>
      <!-- 分配角色弹出层 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <assign-role v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 导入枚举信息
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import employDiolog from './emploDialog.vue'
import AssignRole from './assignRole'
import dayjs from 'dayjs'
// const hireType = {}
// EmployeeEnum.hireType.forEach(item => {
//  hireType[item.id] = item.value
// })
const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})

console.log('枚举信息', EmployeeEnum.hireType, hireType)
export default {
  components: {
    employDiolog,
    AssignRole
  },
  data() {
    return {
      list: [],
      showDialog: false,
      pageParams: {
        page: 1,
        size: 10
      },
      total: 0,
      showDialogRole: false,
      curEmployeId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log(res)
        res.data.rows.forEach(item => {
          item.timeOfEntry = dayjs(item.timeOfEntry).format('YYYY-MM-DD')
        })
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    formatEmployment(id) {
      // console.log('执行一次formatEmployment')
      // // 对后端返回的类型的编码进行翻译 ，还原成 中文
      // const rs = EmployeeEnum.hireType.find(item => item.id === id)
      // return rs.value
      return hireType[id]
    },
    hCurrentChange(curpage) {
      this.pageParams.page = curpage
      this.loadEmployeeList()
    },
    handleSizeChange(curpagesize) {
      this.pageParams.size = curpagesize
      this.loadEmployeeList()
    },
    async doDelRole(id) {
      await delEmployee(id)
      if (this.list.length === 1) {
        this.pageParams.page--
        if (this.pageParams.page < 1) {
          this.pageParams.page = 1
        }
      }
      this.loadEmployeeList()
    },
    hDel(id) {
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.doDelRole(id)
      }).catch((err) => {
        // 用户取消退出
        console.log(err)
      })
    },
    hClose() {
      this.showDialog = false
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      this.total++
      this.pageParams.page = Math.floor(this.total / this.pageParams.size) + 1
      this.loadEmployeeList()
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        // const object = EmployeeEnum.hireType.find(item => item.id === key)
        obj['formOfEmployment'] = hireType[key]
        console.log(obj['formOfEmployment'], 111111)
        return Object.values(obj)
      })

      return { header, data }
    },
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployeeList(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hAssignRole({ id }) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
    }
  }
}
</script>
